<?php
namespace Wx\Model;

class SearchModel extends BaseModel
{

    /**
     * 关键词查询商品
     */
    public function keyGoods()
    {
        $key = I('keyGoods');
        // $limit=10;
        // $page=$page?$page:0;
        // $start=$page*$limit;

        $m = M('goods');
        $field = [
            'goodsId',
            'goodsName',
            'goodsThums',
            'shopId',
            'shopPrice',
        ];

        $where = [
            'isSale' => 1,
            'goodsStatus' => 1,
            'goodsFlag' => 1,
        ];
        if ($key) {
            $where['goodsName'] = ['like', "%{$key}%"];
        }

        $res = $m->field($field)->where($where)->select();

        if ($res) {
            $res = $this->goodsToShop($res);
        }

        return $res;
    }

    /**
     * 整理商品到店铺
     */
    public function goodsToShop($list)
    {
        $temp = [];
        foreach ($list as $v) {
            $temp[$v['shopId']][] = $v;
        }
        unset($list);
        return $temp;
    }

    public function getShopGoods()
    {

        $key = I('key');
        $shop_id = I('shop_id');
        $m = M();

        //查询商品
        $m_goods = M('goods');
        $map = [
            'goodsName' => ['like', "%{$key}%"],
            'isSale' => 1,
            'shopId' => $shop_id,
            'goodsFlag' => 1,
            'goodsStock' => ['gt', 0],
            'goodsStatus' => 1,
        ];

        $goods_list = $m_goods
            ->field('goodsId,goodsImg,goodsName,shopPrice,goodsStock,brandId,goodsCatId1,goodsCatId2,goodsCatId3,shopCatId1,shopCatId2,goodsThums,shopId')
            ->where($map)
            ->select();

        if (isset($goods_list)) {
            $time_star = time();
            $time_end = $time_star - 3600 * 24 * 30;
            $time_star1 = date('Y-m-d H:i:s', $time_end);
            $time_end1 = date('Y-m-d H:i:s', $time_star);
            //
            //for($i=0;$i<count($goods_list);$i++)
            foreach ($goods_list as $k => $v) {
                $goods_id = $v['goodsId'];
                $sql2 = "SELECT * from `__PREFIX__goods_attributes`,`__PREFIX__attributes` where __PREFIX__goods_attributes.goodsId='$goods_id' and isPriceAttr=1 and __PREFIX__goods_attributes.attrId=__PREFIX__attributes.attrId order by __PREFIX__attributes.attrId ASC";
                //echo $sql2;echo '<br>';
                $shuxing_info = $m->query($sql2);

                //dump($shuxing_info);
                if ($shuxing_info) {
                    $goods_list[$k]['is_shuxing'] = 1;

                } else {
                    $goods_list[$k]['is_shuxing'] = 0;
                }
                //dump($goods_list[$k]['is_shuxing']);
                $sql = "SELECT * from `__PREFIX__orders`,`__PREFIX__order_goods` where __PREFIX__orders.orderId=__PREFIX__order_goods.orderId and __PREFIX__order_goods.goodsId='{$goods_id}' and createTime>='$time_star1' and createTime<='$time_end1' and orderStatus='4'";
                $order_list = $m->query($sql);
                $sum = 0;

                if (isset($order_list)) {

                    foreach ($order_list as $value) {
                        $sum += $value['goodsNums'];
                    }
                }
                $goods_list[$k]['yue_xiaoliang'] = $sum;

                $sum = 0;
                $sql = "SELECT * from __PREFIX__goods_appraises where goodsId='{$goods_id}' and isDel='0' ";
                $appraises = $m->query($sql);

                if (isset($appraises)) {
                    $sum = count($appraises);
                }

                $goods_list[$k]['goods_appraises'] = $sum;
                $goods_list[$k]['info'] = '{"goodsId":' . $v['goodsId'] . '}';
                //file_put_contents("tsxx.txt", "\r\n"."是否有属性:".$goods_list[$i]['is_shuxing']."\r\n", FILE_APPEND);
            }
            return ($goods_list);
        }
        return [];
    }

    /**
     * 获取店铺信息
     * @return array 店铺信息列表
     */
    public function getShop($sid = '')
    {

        $lat = I('lat');
        $lon = I('lon');
        $lei = I('lei');
        $paixu = I('paixu', 'zhineng');
        $shaixuan = I('shaixuan');
        $key = I('key');
        //$limit=10;
        $page = I('page', 0);
        $start = $page * $limit;
        if ($sid) {
            $sid = " and s.shopId in ({$sid})";
        }

        $sys_configs = M('sys_configs')->where("fieldName='店铺附近范围'")->getField('fieldCode');
        $fanwei = $sys_configs ? $sys_configs : 200000;

        if (!$lei) {
            $sql = "SELECT s.shopId,s.shopImg,s.shopName,s.isBondShow,s.bondStartTime,s.bondEndTime,s.bond,s.deliveryStartMoney,s.deliveryMoney,s.deliveryCostTime,s.deliveryFreeMoney,s.deliveryStartMoney,s.latitude,s.longitude,s.deliveryType from __PREFIX__shops as s where `shopFlag`='1' and `shopStatus`='1' {$sid}";
        } else {
            $cat_id = $lei;
            $sql = "SELECT s.shopId,s.shopImg,s.shopName,s.isBondShow,s.bondStartTime,s.bondEndTime,s.bond,s.deliveryStartMoney,s.deliveryMoney,s.deliveryCostTime,s.deliveryFreeMoney,s.deliveryStartMoney,s.latitude,s.longitude,s.deliveryType from __PREFIX__shops as s where `shopFlag`='1' and `shopStatus`='1' and (goodsCatId1='{$cat_id}' or goodsCatId2='{$cat_id}' or goodsCatId3='{$cat_id}') {$sid}";
        }

//limit {$start},{$limit}
        if ($paixu == 'zhineng') {
            $sql .= " order by deliveryCostTime ASC ";
        } else if ($paixu == 'qisongjia') {
            $sql .= " order by deliveryStartMoney ASC ";
        }

        $shop_info = M()->query($sql);

        //有商店存在
        if ($shop_info) {
            //平台配送费
            $ptm = $this->getPtDeliveryConfig();
                print_r($ptm);
            for ($i = 0; $i < count($shop_info); $i++) {
                $lat2 = $shop_info[$i]['latitude'];
                $lon2 = $shop_info[$i]['longitude'];
                $shop_info[$i]['juli'] = $this->getDistance($lat, $lon, $lat2, $lon2);
                //计算平台配送费
                if($shop_info[$i]['deliveryType'] == 1){

                }
                if ($shop_info[$i]['juli'] < 1000) {
                    $shop_info[$i]['juli2'] = $shop_info[$i]['juli'] . "米";
                } else {
                    $shop_info[$i]['juli2'] = round($shop_info[$i]['juli'] / 1000, 1) . "KM";
                }
                $shop_info[$i]['juli'] = $shop_info[$i]['juli'] . '';
                if ($shop_info[$i]['juli'] > $fanwei) {
                    array_splice($shop_info, $i, 1);
                    $i--;
                }
            }
                print_r($shop_info);

            //距离排序
            if ($paixu == 'juli') {
                $shop_info = $this->arraySequence($shop_info, 'juli');
            }

            $shop_goods_list = [];

            foreach ($shop_info as $k => $v) {
                //查询商店商品
                $shop_id = $v['shopId'];
                $sql = "SELECT goodsId from `__PREFIX__goods` where `isSale`=1 and shopId='{$shop_id}' and goodsFlag='1'";

                $shop_goods_list = M()->query($sql);
                //dump($shop_goods_list);die;
                //月销量
                if ($shop_goods_list) {
                    $shop_sum = $this->monthSale($shop_goods_list);
                } else {
                    $shop_sum = 0;
                }

                $shop_info[$k]['yue_xiaoliang'] = $shop_sum . '';

                //计算商店评分
                $shop_info[$k]['score'] = $this->calcScore($shop_id);

            }

            if ($paixu == 'xiaoliang') {
                $shop_info = $this->arraySequence($shop_info, 'yue_xiaoliang', 'SORT_DESC');
            }

            //关键词搜索
            if ($key) {
                $temp = [];
                foreach ($shop_info as $k => $v) {
                    if (strpos($v['shopName'], $key) !== false) {
                        $temp[] = $v;
                    }
                }
                $shop_info = $temp;
            }
            if ($shop_info) {
                return $shop_info;
            } else {
                return;
            }

        } else {
            return;
        }
    }

    /**
     * 计算商家评分
     * @param  [int] $shop_id 商店id
     * @param  [arr]  $goods_list
     * @return [int]   $score  商店评分
     */
    public function calcScore($shop_id)
    {

        $sql = "SELECT a.goodsScore,a.serviceScore,a.timeScore,a.content,u.userName,a.anonymity,a.createTime FROM __PREFIX__goods_appraises as a,__PREFIX__users as u where a.shopId='{$shop_id}'  and a.isDel='0' and a.isShow='1' and a.userId=u.userId order by a.createTime DESC ";
        $appraises = M()->query($sql);

        if ($appraises) {
            $ars1 = 0;
            $ars2 = 0;
            $ars_max = count($appraises);
            foreach ($appraises as $key => $v) {
                $ars1 += $v['serviceScore'];
                $ars2 += $v['timeScore'];
                $ars3 += $v['goodsScore'];
            }
            $score = round(($ars1 / $ars_max + $ars2 / $ars_max + $ars3 / $ars_max) / 3, 1);
        } else {
            $score = 5;
        }

        return $score;
    }

    /**
     * 计算月销量
     * @param  [array] $list
     * @return [int]    $shop_sum  商店商品月销量
     */
    public function monthSale($list)
    {
        $time_star = time();
        $time_end = $time_star - 3600 * 24 * 30;
        $time_star1 = date('Y-m-d H:i:s', $time_end);
        $time_end1 = date('Y-m-d H:i:s', $time_star);
        $shop_sum = 0;
        if ($list) {

            $shop_sum = 0;
            //商店商品月销量
            foreach ($list as $key => $row) {
                $goods_id = $row['goodsId'];
                $sql = "SELECT goodsNums from `__PREFIX__orders`,`__PREFIX__order_goods` where __PREFIX__orders.orderId=__PREFIX__order_goods.orderId and __PREFIX__order_goods.goodsId='{$goods_id}' and createTime>='$time_star1' and createTime<='$time_end1' and orderStatus='4'";

                $number = M()->query($sql);

                $sum = 0;
                //商品月销量相加
                if ($number) {
                    foreach ($number as $v) {
                        $sum += $v['goodsNums'];
                    }
                    //$temp_sum=array_column($number,'goodsNums');
                    //$sum+=array_sum($temp_sum);
                }
                $shop_sum += $sum;

            }

        }
        return $shop_sum;
    }

    /**
     * 二维数组根据字段进行排序
     * @params array $array 需要排序的数组
     * @params string $field 排序的字段
     * @params string $sort 排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
     */
    public function arraySequence($array, $field, $sort = 'SORT_ASC')
    {
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }

    public function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
    {
        $EARTH_RADIUS = 6378.137;
        $PI = 3.1415926;
        $radLat1 = $lat1 * $PI / 180.0;
        $radLat2 = $lat2 * $PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s, $decimal);
    }

    //获取平台配送费
    public function getPtDeliveryConfig()
    {
      $m = M('system',C("DB_PREFIX2"),'DB_CONFIG2');
      $data = $m->where("name = 'delivery_config'")->find();
      $ret = unserialize($data['value']);
      var_dump($ret);
      return ;
    }

// utf8  
function mb_unserialize($serial_str) {  
    $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );  
    $serial_str= str_replace("\r", "", $serial_str);  
    return unserialize($serial_str);  
}  
  
// ascii  
function asc_unserialize($serial_str) {  
    $serial_str = preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $serial_str );  
    $serial_str= str_replace("\r", "", $serial_str);  
    return unserialize($serial_str);  
}  
}
